package com.example.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.config.exception.GlobalExcetion;
import com.example.feign.SysTableScriptExtFeignService;
import com.example.feign.SysTableScriptFeignService;
import com.example.system.domain.SysTableScript;
import com.example.system.domain.SysTableScriptExt;
import com.example.system.service.BusSystemTableService;
import com.example.util.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("systable")
public class SystemTableController {

    @Autowired
    private SysTableScriptFeignService sysTableScriptFeignService;

    @Autowired
    private SysTableScriptExtFeignService sysTableScriptExtFeignService;

    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    private BusSystemTableService busSystemTableService;

    @GetMapping("/flushsystable")
    public JSONObject flushSysTable() throws GlobalExcetion {
        System.out.println(appName);
        List<SysTableScript> scriptList=sysTableScriptFeignService.getSysTableScriptList(appName);
        if(scriptList==null||scriptList.size()==0){
            return Results.error("暂无可执行数据");
        }
        for(SysTableScript script:scriptList){
            busSystemTableService.createBusSystemTable(script);
        }
        return Results.success();
    }

    @GetMapping("/flushsystableext")
    public JSONObject flushSysTableExt(@RequestParam("uuid")String uuid) throws GlobalExcetion {
        SysTableScriptExt sysTableScriptExt= sysTableScriptExtFeignService.getSysTableScriptExtById(uuid);
        SysTableScript sysTableScript=sysTableScriptFeignService.getSysTableScriptById(sysTableScriptExt.getTableId());
        List<String> tables=busSystemTableService.getTableList(sysTableScript);
        for(String table:tables){
            String sql=sysTableScriptExt.getSqlScript();
            sql=sql.replaceFirst(sysTableScript.getTableName(),table);
            busSystemTableService.executeSql(sql);
        }
        return Results.success("执行成功");
    }



}
